package com.yxy.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class EchoServer {

	/**
	 * This program implements a simple server 
	 * that listens to port 8189 and echoes back all client
	 * RUN CANN'T TO BE END
	 */
	public static void main(String[] args) {
		// 
		ServerSocket s = null;
		Socket incoming = null;
		try {
			 s = new ServerSocket(8189);
			 incoming = s.accept();
			 
			 InputStream inStream = incoming.getInputStream();
			 OutputStream outStream = incoming.getOutputStream();
			 
			 Scanner in = new Scanner(inStream);
			 //autoFlush;
			 PrintWriter out = new PrintWriter(outStream,true);
			 
			 
			 out.println("Hello, Enter BYE to exit.");
			 //echo client input
			 boolean done = false;
			 
			 while(!done && in.hasNextLine()){
				 String line = in.nextLine();
				 out.println("Echo: " + line);
				 if (line.trim().equals("BYE")) 
					 done = true;
			 }
			 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				incoming.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
